/**
 * Created by hlh on 2015/7/30.
 */


export default class Base {
    constructor() {
    }


    static delegateEvent(obj) {//components) {
        let utils = require('../middleware/utils.js');
        let result;
        let de = function (obj) {
            if (obj.listen && (result = obj.listen())) {
                utils.delegate(
                    result);
            }
            if (obj.cmp) {
                de(obj.cmp);
                for (let i in obj.cmp) {
                    de(obj.cmp[i]);
                }
            }
        };
        de(obj);
    }

    static afterRender(obj) {
        let de = function (obj) {
            if (obj.afterRender) {
                obj.afterRender()
            }
            if (obj.cmp) {
                de(obj.cmp);
                for (let i in obj.cmp) {
                    de(obj.cmp[i]);
                }
            }
        };
        de(obj);
    }

    static fabricate(name, data) {
        var hah = require('./' + name);
        return new hah(data);
    }

    static render(obj,
                  moutNode = 'body>div',
                  position = 'after',
                  clearPre = false) {
        moutNode = document.querySelector(moutNode);
        if (!moutNode) {
            console.error('No valid node');
            return;
        }
        if (clearPre) {
            moutNode.removeChild(moutNode.children[moutNode.children.length - 1]);
        }
        let preRender = "object" === typeof obj ? obj.render() : obj.toString();
        switch (position) {
            case "after":
                moutNode.insertAdjacentHTML('afterend', preRender);
                break;
            case 'before':
                moutNode.insertAdjacentHTML('beforeend', preRender);
                break;
            case 'inner':
                moutNode.innerHTML = preRender;
                break;
            default:
                console.log('test');
        }

        /*    let components = [obj];
         for (let index in obj.cmp) {
         components.push(obj.cmp[index]);
         }*/
        if ("object" === typeof obj) {
            this.afterRender(obj);
            this.delegateEvent(obj)//components);
        }
    }
}